package com.yu.mall.runnable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yu.mall.entity.ProductInfo;
import com.yu.mall.enums.StatusEnum;
import com.yu.mall.mapper.ProductInfoMapper;
import com.yu.mall.util.JDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class ProductRunnable implements Runnable {

    private ProductInfoMapper productInfoMapper;

    private String typeCode;

    private String typeName;

    private CountDownLatch countDownLatch;

    public ProductRunnable(ProductInfoMapper productInfoMapper, String typeCode, String typeName, CountDownLatch countDownLatch) {
        this.productInfoMapper = productInfoMapper;
        this.typeCode = typeCode;
        this.typeName = typeName;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        getPrdListByType(typeCode,typeName);
    }

    private void getPrdListByType(String typeCode,String typeName) {
        try {
            int pageNum = 0;
            boolean loopFlag = true;
            while (loopFlag && pageNum < 100) {
                log.info("" + (loopFlag && pageNum< 100) );
                pageNum++;
                Map<String, Object> map = JDUtils.productGetSkuByPage(typeCode, pageNum);
                if (map.isEmpty()) {
                    break;
                }
                JSONObject data = (JSONObject) map.get("data");
                if (pageNum >= data.getIntValue("pageCount")) {
                    loopFlag = false;
                }
                List<Long> skuIds = JSONArray.parseArray(data.get("skuIds").toString(),Long.class);
                if(CollectionUtils.isEmpty(skuIds)){
                    continue;
                }
                ExecutorService threadPool  = Executors.newFixedThreadPool(5);
                CountDownLatch countDown = new CountDownLatch(skuIds.size());
                for (Long skuId : skuIds) {
                    threadPool.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONArray productCheck = JDUtils.productCheck(skuId.toString(), "");
                                if(productCheck != null ) {
                                    for (int i = 0; i < productCheck.size(); i++) {
                                        String saleState = productCheck.getJSONObject(i).getString("saleState");
                                        if("1".equals(saleState)) {
                                            String sku = skuId.toString();
                                            Map<String, String> newStockById = JDUtils.getNewStockById(sku, "");
                                            if("有货".equals(newStockById.get("stockStateDesc"))) {
                                                Map<String, Object> prdMap = JDUtils.productGetDetail(sku, null);
                                                if (prdMap.isEmpty()) {
                                                    continue;
                                                }
                                                Map<String, Object> priceMap = JDUtils.priceGetSellPrice(sku);
                                                if (priceMap.isEmpty()) {
                                                    continue;
                                                }
                                                JSONObject prdJson = (JSONObject) prdMap.get("data");
                                                JSONArray priceJsonArr = (JSONArray) priceMap.get("data");
                                                if (priceJsonArr.size() < 1) {
                                                    continue;
                                                }
                                                JSONObject priceJson = priceJsonArr.getJSONObject(0);
                                                ProductInfo item = new ProductInfo();
                                                item.setSkuId(sku);
                                                item.setName(prdJson.getString("name"));
                                                item.setImagePath(prdJson.getString("imagePath"));
                                                item.setBrand(prdJson.getString("brandName"));
                                                item.setJdPrice(priceJson.getBigDecimal("jdPrice"));
                                                item.setPrice(priceJson.getBigDecimal("price"));
                                                item.setRate(item.getPrice().divide(item.getJdPrice(), 2, RoundingMode.HALF_UP));
                                                item.setTypeCode(typeCode);
                                                item.setTypeName(typeName);
                                                item.setIsdel("0");
                                                ProductInfo selectByPrimaryKey = productInfoMapper.selectByPrimaryKey2(sku);
                                                if(selectByPrimaryKey !=null) {
                                                    item.setStatus(selectByPrimaryKey.getStatus());
                                                    item.setIsLaobao(selectByPrimaryKey.getIsLaobao());
                                                    item.setCreateDatetime(selectByPrimaryKey.getCreateDatetime());
                                                    item.setUpdateDatetime(new Date());
                                                    productInfoMapper.updateByPrimaryKey(item);
                                                }else {
                                                    item.setStatus(StatusEnum.ON.getCode());
                                                    item.setIsLaobao(false);
                                                    item.setCreateDatetime(new Date());
                                                    item.setUpdateDatetime(new Date());
                                                    productInfoMapper.insertSelective(item);
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                log.error("按类型查询商品列表，typeCode:{},更新单个sku失败", typeCode, e);
                            } finally {
                                countDown.countDown();
                                log.info(""+ countDown);
                            }
                        }
                    });
                }
                countDown.await();
                threadPool.shutdown();
            }
        } catch (Exception e) {
            log.error("按类型查询商品列表失败，typeCode:{}", typeCode, e);
        }finally {
            countDownLatch.countDown();
        }
    }
}
